package com.ruyuan.engine.service;

import com.ruyuan.engine.pojo.ClientLog;
import com.ruyuan.engine.pojo.RuleComplexParam;
import com.ruyuan.engine.utils.Constants;
import com.ruyuan.engine.utils.HBaseUtils;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import java.util.HashMap;
import java.util.Set;

public class BaseRuleServiceImpl implements BaseRuleService {

    static HTable hTable;

    static {
        hTable = HBaseUtils.initHbaseClient(Constants.HBASE_TABLE);
    }

    /**
     * 查询规则中的条件，和事件的属性是否匹配
     * */
    @Override
    public boolean mathRuleByCondition(ClientLog clientLog, RuleComplexParam ruleComplexParam) {
        //从规则中取出前端封装过来的条件
        HashMap<String, String> baseRuleParams = ruleComplexParam.getBaseRuleParams();

        //匹配和clientLog的条件是否相等
        Set<String> conditionNames = baseRuleParams.keySet();
        Get get = new Get(clientLog.getUserNo().getBytes());
        for (String cName:conditionNames) {
            get.addColumn("profile".getBytes(),cName.getBytes());
        }
        //查询hbase
        String value = "";
        try {
            Result result = hTable.get(get);
            for (String cName:conditionNames) {
                byte[] value1 = result.getValue("profile".getBytes(), cName.getBytes());
                if (value1 != null) {
                    value = new String(value1);
                    if (!value.equals(baseRuleParams.get(cName))) {
                        return false;
                    }
                }else {
                    return false;
                }
            }
            //规则能够匹配
            return true;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
